﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace RobotMapper
{
    internal class RobotMapperConfig<Source, Target> : IRobotMapperConfig<Source, Target>
    {
        /// <summary>
        /// 将源属性与目标属性绑定 可按照自定义规则
        /// </summary>
        /// <param name="source">源属性绑定规则</param>
        /// <param name="target">目标属性</param>
        public void Bind(Func<Source, object> source, Expression<Func<Target, object>> target)
        {
            if (GlobalConfig.BindRoles.Count(a => a.SourceType == typeof(Source) && a.TargetType == typeof(Target)) > 0) return;
            //获取目标属性名称
            var tProName = RobotMapperHelper.GetPropertyName(target);
            GlobalConfig.BindRoles.Add(new BindRole()
            {
                SourceType = typeof(Source),
                TargetType = typeof(Target),
                SourceFunc = (a) =>
                {
                    return source?.Invoke((Source)a);
                },
                TargetPropertyName = tProName
            });
        }

        /// <summary>
        /// 添加目标的忽略属性 单个添加
        /// </summary>
        /// <param name="targetIgnore">目标属性</param>
        public void Ignore(Expression<Func<Target, object>> targetIgnore)
        {
            //获取目标属性名称
            var tProName = RobotMapperHelper.GetPropertyName(targetIgnore);
            var role = GlobalConfig.IgnoreRoles.SingleOrDefault(a => a.SourceType == typeof(Source) && a.TargetType == typeof(Target));
            if (role == null)
            {
                var newRole = new IgnoreRole()
                {
                    SourceType = typeof(Source),
                    TargetType = typeof(Target),
                };
                newRole.IgnoreMembers.Add(tProName);
                GlobalConfig.IgnoreRoles.Add(newRole);
            }
            else
            {
                if (!role.IgnoreMembers.Contains(tProName))
                    role.IgnoreMembers.Add(tProName);
            }
        }

        /// <summary>
        /// 添加目标的忽略属性 批量添加
        /// </summary>
        /// <param name="ignoreProperty">目标属性</param>
        public void Ignore(params string[] ignoreProperty)
        {
            //获取目标属性名称
            var role = GlobalConfig.IgnoreRoles.SingleOrDefault(a => a.SourceType == typeof(Source) && a.TargetType == typeof(Target));
            if (role == null)
            {
                var newRole = new IgnoreRole()
                {
                    SourceType = typeof(Source),
                    TargetType = typeof(Target),
                };
                newRole.IgnoreMembers.AddRange(ignoreProperty.ToList());
            }
            else
            {
                var newMembers = ignoreProperty.Except(role.IgnoreMembers).ToList();
                role.IgnoreMembers.AddRange(newMembers);
            }
        }
    }
}
